//
//  ToWebView.m
//  hengqintong
//
//  Created by DongWei on 2019/11/11.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import <WebKit/WebKit.h>
#import "ToWebView.h"
#import "IWCScanBarCodeViewController.h"

@interface ToWebView ()<WKNavigationDelegate, WKUIDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *wkWeb;
@property (nonatomic, strong) UIProgressView *myProgressView;
@property (nonatomic, copy) IWCScanBarCodeViewController *QRVC;

@end

@implementation ToWebView

#pragma mark - getter and setter
- (UIProgressView *)myProgressView
{
  if (_myProgressView == nil) {
    _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 65, [UIScreen mainScreen].bounds.size.width, 2)];
    _myProgressView.backgroundColor = [UIColor blueColor];
    _myProgressView.trackTintColor = [UIColor whiteColor];
    _myProgressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
  }
  
  return _myProgressView;
}

-(WKWebView *)wkWeb
{
  if (_wkWeb == nil) {
    _wkWeb = [[WKWebView alloc]initWithFrame:CGRectZero];
    _wkWeb.navigationDelegate = self;
    _wkWeb.UIDelegate = self;
  }
  return _wkWeb;
}

-(void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  
  // 监听 js 调用 iOS 的方法名
 
  [self.wkWeb.configuration.userContentController addScriptMessageHandler:self name:@"startCameraScan"];
  [self.wkWeb.configuration.userContentController addScriptMessageHandler:self name:@"openHTMLWithURL"];
  [self.wkWeb.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
  [self.wkWeb.configuration.userContentController addScriptMessageHandler:self name:@"StartDownload"];
  [self.wkWeb.configuration.userContentController addScriptMessageHandler:self name:@"StartAlbum"];
}

-(void)viewWillDisappear:(BOOL)animated{
  [super viewWillDisappear:animated];
  
 
  [self.wkWeb.configuration.userContentController removeScriptMessageHandlerForName:@"startCameraScan"];
  [self.wkWeb.configuration.userContentController removeScriptMessageHandlerForName:@"openHTMLWithURL"];
  [self.wkWeb.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"];
  [self.wkWeb.configuration.userContentController removeScriptMessageHandlerForName:@"StartDownload"];
  [self.wkWeb.configuration.userContentController removeScriptMessageHandlerForName:@"StartAlbum"];
}

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  
  //  NSLog(@"URL:%@ AndName:%@", self.url, self.name);
  [self.view setBackgroundColor:[UIColor whiteColor]];
  
  // 创建一个导航栏
  UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
  [navBar setBackgroundColor:[UIColor whiteColor]];
  navBar.translucent = NO;
  
  // 添加进度条
  [self.myProgressView setFrame:CGRectMake(0, navBar.frame.size.height + navBar.frame.origin.y + 1, self.view.frame.size.width, 2)];
  
  // 自定义导航栏的title，用UILabel实现
  UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
  titleLabel.text = self.name;
  
  // 创建导航栏组件
  UINavigationItem *navItem = [[UINavigationItem alloc] init];
  
  // 设置自定义的title
  navItem.titleView = titleLabel;
  
  // 创建左侧按钮
  UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:self.close style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonClick)];
  
  // 添加左侧按钮
  [navItem setRightBarButtonItem:rightButton animated:false];
  // 把导航栏组件加入导航栏
  [navBar pushNavigationItem:navItem animated:false];
  
  UIView *splitView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 1)];
  [splitView setBackgroundColor:[UIColor colorWithRed:0.961 green:0.961 blue:0.961 alpha:1]];
//  [splitView setBackgroundColor:[UIColor redColor]];
  
  [self.wkWeb setFrame:CGRectMake(0, 67, self.view.frame.size.width, self.view.frame.size.height - 67)];
  [self.wkWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
  [self.wkWeb addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  
  // 导航栏添加到view上
  [self.view addSubview:navBar];
  [self.view addSubview:self.myProgressView];
  [self.view addSubview:splitView];
  [self.view addSubview:_wkWeb];
}

#pragma mark 处理 WKWebView 的加载动作
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  NSLog(@"开始加载网页");
  //开始加载网页时展示出progressView
  self.myProgressView.hidden = NO;
  //开始加载网页的时候将progressView的Height恢复为1.5倍
  self.myProgressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
  //防止progressView被网页挡住
  [self.view bringSubviewToFront:self.myProgressView];
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  NSLog(@"加载完成");
  //加载完成后隐藏progressView
  self.myProgressView.hidden = YES;
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  NSLog(@"加载失败");
  //加载失败同样需要隐藏progressView
  self.myProgressView.hidden = YES;
}

-(void)rightButtonClick{
  [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 监听 JS 方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
  __weak __typeof__(self) weakSelf = self;
  //    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
  NSLog(@"body:%@",message.body);
 
  // 开启二维码扫描
  if ([message.name isEqualToString:@"startCameraScan"]) {
    NSLog(@"打开二维码");
    _QRVC = [[IWCScanBarCodeViewController alloc]init];
    _QRVC.IWCQRCodeSuccessBlock = ^(IWCScanBarCodeViewController *ScanVC, NSString *resultStr){
      [weakSelf startCameraScanCallback:resultStr andVC:ScanVC];
    };
    [self presentViewController:_QRVC animated:YES completion:nil];
  }
  
  // 调用浏览器加载 URL
  if([message.name isEqualToString:@"openHTMLWithURL"]) {
    [self openHTMLWithURL:message.body];
  }
  
  // 退出 webView
  if ([message.name isEqualToString:@"GoBack"]) {
    [self dismissViewControllerAnimated:YES completion:nil];
  }
  
  // 下载图片并保存至本地相册
  if ([message.name isEqualToString:@"StartDownload"]) {
    UIAlertController* ac = [UIAlertController  alertControllerWithTitle: @"提示" message: @"开始下载" preferredStyle: UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
    
//    NSURL *url = [NSURL URLWithString:message.body];
  
  }
  
  // 打开相册并选取照片
  if ([message.name isEqualToString:@"StartAlbum"]) {
    UIImagePickerController *vc = [[UIImagePickerController alloc] init];
    vc.delegate = self;
    //    vc.allowsEditing = YES;
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:vc animated:YES completion:nil];
  }
}

#pragma mark -- 图片选择回调
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
  UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
  NSData *tmpData = UIImageJPEGRepresentation(image, 0.3f);
  NSString *imageBase64Str = [tmpData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
  
  [self StartAlbumCallback:imageBase64Str];
  
  [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 关闭图片选择
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 调用 js 方法实现相册选择的回调
-(void)StartAlbumCallback:(NSString *)callback{
  NSString *tmpStr = [@"a.jpeg,data:image/jpeg;base64," stringByAppendingString:callback];
  
  NSString *jsStr = [NSString stringWithFormat:@"StartAlbumCallback('%@')",tmpStr];
  [self.wkWeb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {}];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
  if (error) {
    UIAlertController* ac = [UIAlertController  alertControllerWithTitle: @"提示" message: @"图片保存失败" preferredStyle: UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
    
    NSString *jsStr = [NSString stringWithFormat:@"saveImage('%@')",@"保存失败"];
    [self.wkWeb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {}];
  } else {
    UIAlertController* ac = [UIAlertController  alertControllerWithTitle: @"提示" message: @"图片保存成功" preferredStyle: UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
    
    NSString *jsStr = [NSString stringWithFormat:@"saveImage('%@')",@"保存成功"];
    [self.wkWeb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {}];
  }
}

#pragma mark - 观察者响应
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]) {
    self.myProgressView.progress = self.wkWeb.estimatedProgress;
    
    if (self.myProgressView.progress == 1) {
      /*
       *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
       *动画时长0.25s，延时0.3s后开始动画
       *动画结束后将progressView隐藏
       */
      __weak typeof (self)weakSelf = self;
      [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
        weakSelf.myProgressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
      } completion:^(BOOL finished) {
        weakSelf.myProgressView.hidden = YES;
      }];
    }
  }else {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  }
}

-(void)startCameraScanCallback: (NSString *)callback andVC:(IWCScanBarCodeViewController *)scanVC{
  // 正确的二维码扫描后可以根据,分割为三个字符串
  NSArray *tmpArr = [callback componentsSeparatedByString:@","];
  if(tmpArr.count == 3){
    NSDictionary *callbackDic = @{@"result_string":callback,@"result_type":@1};
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callbackDic options:0 error:0];
    
    // 将 NSData 类型数据转为 string
    NSString *dataStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *jsStr = [NSString stringWithFormat:@"startCameraScanCallback('%@')",dataStr];
    
    [self.wkWeb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
      NSLog(@"%@----%@",result, error);
    }];
    
    [scanVC dismissViewControllerAnimated:YES completion:nil];
  }else{
    UIAlertController* ac = [UIAlertController  alertControllerWithTitle: @"提示" message: @"識別二維碼失敗" preferredStyle: UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil]];
    [scanVC presentViewController:ac animated:YES completion:nil];
    [scanVC startQRCodeReading];
  }
}

-(void) openHTMLWithURL:(NSString *)url {
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
